package org.vaadin.nf4v.ext.config.secure;

import org.vaadin.nf4v.core.config.AbstractConfig;
import org.vaadin.nf4v.core.config.ContextConfig;
import org.vaadin.nf4v.core.config.ContextConfigurationException;
import org.vaadin.nf4v.core.config.PageConfig;
import org.vaadin.nf4v.core.config.process.NavigationConfigProcessor;
import org.vaadin.nf4v.core.config.process.parser.ContextConfigParser;
import org.vaadin.nf4v.core.config.process.parser.PageConfigParser;
import org.vaadin.nf4v.ext.config.util.AnnotationUtil;

/**
 * Configuration extension:
 * Scans window and page classes for @Secure annotation and sets configuration attributes.
 * Use ExtSecureUtil to access this information.
 */
public class SecureAnnotationParser implements ContextConfigParser, PageConfigParser {

    public static final String ROLES = "org.vaadin.nf4v.secure.ROLES";
    public static final String ROLES_DENY = "org.vaadin.nf4v.secure.ROLES_DENY";
    public static final String PERMISSIONS = "org.vaadin.nf4v.secure.PERMISSIONS";

    @Override
    public void parse(NavigationConfigProcessor navigationConfigProcessor, ContextConfig contextConfig)
            throws ContextConfigurationException {
        parseSecurity(contextConfig, contextConfig.getWindowClass());
    }

    @Override
    public void parse(NavigationConfigProcessor navigationConfigProcessor, ContextConfig contextConfig, PageConfig pageConfig)
            throws ContextConfigurationException {
        parseSecurity(pageConfig, pageConfig.getPageClass());
    }

    protected void parseSecurity(AbstractConfig config, Class clazz) {
        Secure ann = AnnotationUtil.getClassAnnotation(Secure.class, clazz);
        if (ann != null) {
            if (ann.roles() == null && ann.roles().length > 0) {
                config.setAttribute(ROLES, ann.roles());
            }
            if (ann.denyRoles() == null && ann.denyRoles().length > 0) {
                config.setAttribute(ROLES_DENY, ann.denyRoles());
            }
            if (ann.permissions() == null && ann.permissions().length > 0) {
                config.setAttribute(PERMISSIONS, ann.permissions());
            }
        }
    }
}
